import { DEFAULT_PAGE_CONFIG } from '@/constants/global.const';
import type { ParamsType } from '@ant-design/pro-provider';
import type { ActionType, ProTableProps } from '@ant-design/pro-table';
import { message } from 'antd';
import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';
// import { v4 as uuidv4 } from 'uuid';

import CommonProTable from './CommonTable';

type TProps = ProTableProps<Record<string, any>, ParamsType, string> & {
  fetchAction?: (...args: any[]) => Promise<any>;
  fetchCallBack?: TAnyFunction;
  fetchErrorBack?: TAnyFunction;
  loading?: boolean;
  needUuid?: boolean; // 是否需要前端生成uuid
  reqCurrentKey?: string; // 传递给接口当前分页key值
  reqPageSizeKey?: string; // 传递给接口当前分页key值
  resTotalKey?: string; // 接口返回的数据总数key值
  resCurrentKey?: string; // 接口返回的当前第几页
  resPageSizeKey?: string; // 接口返回的当前第几页
  dataKey?: string; // 列表数据存放的key值，不传默认就是data下的数组
  extraParams?: Record<string, any>; // 额外传入接口的参数
  params?: Record<string, any>;
  needFilterChildren?: boolean; // 是否需要过滤掉空children，用于树形表格展示数据时过滤
  ref?: any;
};

/**
 * 基于proTable封装的table组件，定义了request及一些属性
 */
const CommonTable: React.FC<TProps> = forwardRef((props, ref) => {
  const {
    fetchAction,
    needUuid,
    reqCurrentKey = 'pageNo',
    reqPageSizeKey = 'size',
    dataKey,
    loading,
    resTotalKey = 'totalCount',
    resCurrentKey = 'currPage',
    resPageSizeKey = 'pageSize',
    fetchCallBack,
    fetchErrorBack,
    needFilterChildren = false,
    extraParams = {},
    params: customParams,
    ...rest
  } = props;
  const [page, setPage] = useState({ ...DEFAULT_PAGE_CONFIG });
  const [fetchLoading, setFetchLoading] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  /**
   * 重新获取表格数据
   * @param reset 是否重置
   * @returns void
   */
  const reload = (reset = false) => {
    debugger
    if (!actionRef.current) {
      return;
    }
    if (reset) {
      actionRef.current?.reloadAndRest?.();
    } else {
      actionRef.current?.reload();
    }
  };

  // 解决删除最后一页唯一一条数据后页码不往前一页的问题
  const reloadAfterDelete = () => {
    const { current, total = 0, pageSize } = page || {};
    if (current <= 1) {
      reload();
    } else {
      // 当前是最后一页且只有一条
      if (current === Math.ceil(total / pageSize) && total % pageSize === 1) {
        setPage({
          ...page,
          current: current - 1,
        });
      } else {
        reload();
      }
    }
  };

  useImperativeHandle(
    ref,
    (): TTableAction => ({
      reload,
      reloadAfterDelete,
      page,
    }),
  );

  const filterTreeEmptyChild = (data: any[]) => {
    const afterData = data.map((item) => {
      if (item.children?.length === 0) {
        delete item.children;
      } else if (item.children?.length) {
        filterTreeEmptyChild(item.children);
      }
      return item;
    });
    return afterData;
  };

  // 获取列表数据方法
  const fetchData = async (params: any) => {
    if (!fetchAction) return [];

    setFetchLoading(true);

    try {
      const { current, pageSize: pageSizeParam, ...restParams } = params;
      const condition = {
        [reqCurrentKey]: current,
        [reqPageSizeKey]: pageSizeParam,
        ...restParams,
        ...extraParams,
      };
      const { code, data = [], msg } = await fetchAction(condition);
      setFetchLoading(false);
      if (code === 200) {
        console.log('data=>>>', data)
        const dataList = dataKey ? (data || {})[dataKey] : data;
        setPage({
          total: data[resTotalKey],
          current: data[resCurrentKey],
          // pageSize: data[resPageSizeKey],
          pageSize: 10,
        });
        fetchCallBack?.(data);
        if (needUuid) {
          // 需要的uuid的话前端自己生成一个
          const res = (dataList || []).map((o: any) => ({
            ...o,
            uuid: Math.random().toString(32).slice(2), // 如果返回的数据没有唯一id，前端自己生成一个
          }));
          return res;
        }
        if (needFilterChildren) {
          return filterTreeEmptyChild(dataList);
        }
        return dataList;
      } else {
        fetchErrorBack?.();
        message.error(msg);
      }
    } catch (err) {}
    setFetchLoading(false);
    return [];
  };

  return (
    <CommonProTable
      loading={loading || fetchLoading}
      // actionRef={actionRef}
      pagination={{ ...page }}
      params={{ ...customParams }}
      request={async (params) => {
        const resData = await fetchData({ ...params });
        return {
          data: resData,
          success: true,
        };
      }}
      {...rest}
    />
  );
});

export default CommonTable;
